﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Text;
using System.Xml;
using System.IO;
/// <summary>
/// CreateHtmlArticle 的摘要说明
/// </summary>
public class CreateHtmlArticle
{
	public CreateHtmlArticle()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}
    /// <summary>
    /// 生成短篇文章网页
    /// </summary>
    /// <param name="articleId">文章ID</param>
    /// <returns></returns>
    public bool CreateShortHtml(string articleId, out string errorMsg)
    {
        string title, author, contentId, content, typeId, typeName;
        bool ok = true;
        ok = GetShortArticle(articleId, out title, out author, out contentId, out content, out typeId, out typeName, out errorMsg);
        if(!ok)
        {
            return false;
        }
        ok = CreateShortArticle(articleId, title, author, contentId, ref content, typeId, typeName, out errorMsg);
        if(!ok)
        {
            return false;
        }
        return true;
    }
    /// <summary>
    /// 生成长篇文章网页
    /// </summary>
    /// <param name="articleId">文章Id</param>
    /// <returns></returns>
    public bool CreateLongHtml(string articleId, out string errorMsg)
    {
        string htmlHead, htmlTitleEnd, htmlContentTitle, htmlContentHead, htmlEnd, htmlPage, htmlPageEnd;
        XmlDocument doc = new XmlDocument();
        doc.Load(HttpContext.Current.Server.MapPath("~\\App_Data\\ArticleContentTemplate.xml"));
        XmlElement root = doc.DocumentElement;
        htmlHead = root.SelectSingleNode("htmlHead").InnerText;
        htmlTitleEnd = root.SelectSingleNode("htmlTitleEnd").InnerText;
        htmlContentTitle = root.SelectSingleNode("htmlContentTitle").InnerText;
        htmlContentHead = root.SelectSingleNode("htmlContentHead").InnerText;
        htmlPage = root.SelectSingleNode("htmlPage").InnerText;
        htmlPageEnd = root.SelectSingleNode("htmlPageEnd").InnerText;
        htmlEnd = root.SelectSingleNode("htmlEnd").InnerText;

        string command = "select a.ArticleTitle,a.Author,c.ContentId,c.ContentPart,p.TypeId,p.TypeName from " +
            " (ArticleLongTitle a inner join ArticleType p on a.ArticleType=p.TypeId) " +
            " inner join ArticleLongContent c on a.ArticleId=c.ArticleId " +
            " where a.ArticleId=" + articleId + " order by c.ContentId";
        OleDbCommand cmd = new OleDbCommand(command, con);
        try
        {
            //con.Open();
            DataSet ds = new DataSet();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            da.Fill(ds);
            int pageCount = ds.Tables[0].Rows.Count;
            for(int i = 1; i <= pageCount; i++)
            {
                using(StreamWriter w = new StreamWriter(HttpContext.Current.Server.MapPath("~\\html\\") + articleId + "_" + i.ToString() + ".html", false, System.Text.Encoding.UTF8))
                {
                    //ds 的列值 0:title 1:author 2:contentId 3:content 4:typeId 5:typeName
                    w.Write(htmlHead + ds.Tables[0].Rows[i-1][0].ToString() + " 第" + i.ToString() + "页cid=" + ds.Tables[0].Rows[i-1][2].ToString() + htmlTitleEnd +
                        htmlContentTitle + "<div id='nav'><a href='articlemenu" +//<a href='../default.aspx'>首页</a>
                        ds.Tables[0].Rows[i-1][4].ToString() + "_1.html'>" + ds.Tables[0].Rows[i-1][5].ToString() +
                        "</a></div><span id='visitPage'>" + articleId + "</span>" + ds.Tables[0].Rows[i - 1][0].ToString() + " (" + i.ToString() + ") <span class='author'>作者：" + 
                        ds.Tables[0].Rows[i-1][1].ToString() + "</span>" + htmlContentHead + ds.Tables[0].Rows[i-1][3].ToString() +
                        htmlPage + GetPageCode(articleId, i, pageCount) + htmlPageEnd + htmlEnd);
                    w.Close();
                }
            }
            errorMsg = "";
            return true;
        }
        catch(Exception exs)
        {
            errorMsg = exs.Message;
            return false;
        }
        //finally
        //{
        //    con.Close();
        //}
    }
    /// <summary>
    /// 生成章节文章网页
    /// </summary>
    /// <param name="articleId">文章ID</param>
    /// <returns></returns>
    public bool CreateChapterHtml(string articleId, out string errorMsg)
    {
        string command = "select t.TypeId, t.TypeName,c.ChapterId,c.ChapterName,a.ArticleTitle, a.Author from (ArticleChapter c inner join " +
            "ArticleLongTitle a on c.ArticleId=a.ArticleId) inner join ArticleType t on a.ArticleType=t.TypeId " +
            " where a.ArticleId=" + articleId + " ORDER BY c.ShowOrder";

        OleDbCommand cmd = new OleDbCommand(command, con);
        try
        {
            DataSet ds = new DataSet();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            da.Fill(ds);
            string typeId, typeName, title, author, chapterId, chapterName;
            typeId = ds.Tables[0].Rows[0][0].ToString();
            typeName = ds.Tables[0].Rows[0][1].ToString();
            title = ds.Tables[0].Rows[0][4].ToString();
            author = ds.Tables[0].Rows[0][5].ToString();
            int chapterCount = ds.Tables[0].Rows.Count;
            bool ok = true;
            for(int n = 0; n < chapterCount; n++)
            {
                if(n + 1 < chapterCount)
                {
                    ok = CreateChapterHtmlPage(articleId, title, typeId, typeName, author, ds.Tables[0].Rows[n][2].ToString(),
                        ds.Tables[0].Rows[n][3].ToString(), n, ds.Tables[0].Rows[n + 1][2].ToString(), chapterCount, out errorMsg);
                }
                else
                {
                    ok = CreateChapterHtmlPage(articleId, title, typeId, typeName, author, ds.Tables[0].Rows[n][2].ToString(),
                        ds.Tables[0].Rows[n][3].ToString(), n, "no", chapterCount, out errorMsg);//没有下一章，就是 no
                }
                if(!ok)
                {
                    return false;
                }
            }
            errorMsg = "";
            return true;
        }
        catch(Exception exs)
        {
            errorMsg = exs.Message;
            return false;
        }
    }

    protected  bool CreateChapterHtmlPage(string articleId,string title, string typeId, string typeName, string author, string chapterId, string chapterName, int currentChapter, string nextChapterId, int chapterCount, out string errorMsg)
    {
        string htmlHead, htmlTitleEnd, htmlContentTitle, htmlContentHead, htmlEnd, htmlPage, htmlPageEnd;
        XmlDocument doc = new XmlDocument();
        doc.Load(HttpContext.Current.Server.MapPath("~\\App_Data\\ArticleContentTemplate.xml"));
        XmlElement root = doc.DocumentElement;
        htmlHead = root.SelectSingleNode("htmlHead").InnerText;
        htmlTitleEnd = root.SelectSingleNode("htmlTitleEnd").InnerText;
        htmlContentTitle = root.SelectSingleNode("htmlContentTitle").InnerText;
        htmlContentHead = root.SelectSingleNode("htmlContentHead").InnerText;
        htmlPage = root.SelectSingleNode("htmlPage").InnerText;
        htmlPageEnd = root.SelectSingleNode("htmlPageEnd").InnerText;
        htmlEnd = root.SelectSingleNode("htmlEnd").InnerText;
        string command = "select ContentId, ContentPart from ArticleLongContent where ChapterId=" + chapterId;
        OleDbCommand cmd = new OleDbCommand(command, con);
        try
        {
            DataSet ds = new DataSet();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            da.Fill(ds);
            int pageCount = ds.Tables[0].Rows.Count;
            for(int i = 1; i <= pageCount; i++)
            {
                using(StreamWriter w = new StreamWriter(HttpContext.Current.Server.MapPath("~\\html\\") + articleId + "_" + chapterId + "_" + i.ToString() + ".html", false, System.Text.Encoding.UTF8))
                {
                    w.Write(htmlHead + title + "-" + chapterName + "-" + typeName + ",page=" + i.ToString() + ",contentid=" + ds.Tables[0].Rows[i - 1][0].ToString() + htmlTitleEnd +
                        htmlContentTitle + "<div id='nav'><a href='articlemenu" +//<a href='../default.aspx'>首页</a>
                        typeId + "_1.html'>" + typeName + "</a></div><span id='navTitle'><a href='index_" +
                        articleId + ".html'>" + title + "</a> </span> " + chapterName + " (" + i.ToString() + ") <span class='author'>作者：" +
                        author + "</span>" + htmlContentHead + ds.Tables[0].Rows[i - 1][1].ToString() +
                        htmlPage + GetPageCodeChapter(articleId, chapterId, currentChapter, i, pageCount, nextChapterId, chapterCount) + htmlPageEnd + htmlEnd);
                    w.Close();
                }
            }
            errorMsg = "";
            return true;
        }
        catch(Exception exs)
        {
            errorMsg = exs.Message;
            return false;
        }
    }
    protected string GetPageCodeChapter(string articleId, string chapterId, int currentChapter, int currentPage, int totalPage, string nextChapterId, int chapterCount)
    {
        string nextChapter = "";
        if(nextChapterId != "no")//不是最后一章
        {
            nextChapter = " <span class='nextChapter'><a href='" + articleId + "_" + nextChapterId + "_1.html'>下一章" + "</a> </span>";
        }
        string pageCode = "";
        if(currentPage == 1)
        {
            if(totalPage > 1)
            {
                pageCode = "第1页 " + "<a href='" + articleId + "_" + chapterId + "_2.html'>下一页</a> ";
            }
            else
            {
                if((currentChapter + 1) < chapterCount)//不是最后一章
                {
                    pageCode = "第1页 <a href='" + articleId + "_" + nextChapterId + "_1.html'>下一页" + "</a> ";
                }
                else
                {
                    pageCode = "第1页 ";
                }
            }
        }
        else if(currentPage == totalPage)//当前章节的最后一页
        {
            pageCode = "<a href='" + articleId + "_" + chapterId + "_" + (currentPage - 1).ToString() + ".html'>上一页</a> " + "第" + totalPage.ToString() + "页 ";
            if((currentChapter + 1) < chapterCount)//不是最后一章
            {
                pageCode += "<a href='" + articleId + "_" + nextChapterId + "_1.html'>下一页" + "</a> ";
            }
        }
        else
        {
            pageCode = "<a href='" + articleId + "_" + chapterId + "_" + (currentPage - 1).ToString() + ".html'>上一页</a> "
                + "第" + currentPage.ToString() + "页 " + "<a href='" + articleId + "_" + chapterId + "_" + (currentPage + 1).ToString() + ".html'>下一页</a> ";
        }
        for(int k = 1; k <= totalPage; k++)
        {
            if(k == currentPage)
            {
                pageCode += "<a id='currentPage' href='" + articleId + "_" + chapterId + "_" + k.ToString() + ".html'>" + k.ToString() + "</a> ";
            }
            else
            {
                pageCode += "<a href='" + articleId + "_" + chapterId + "_" + k.ToString() + ".html'>" + k.ToString() + "</a> ";
            }
        }
        if((currentChapter + 1) < chapterCount)//不是最后一章
        {
            pageCode += nextChapter;
        }
        pageCode += "<a href='index_" + articleId + ".html'>回目录</a>";
        return pageCode;
    }
    protected string GetPageCode(string articleId, int currentPage, int totalPage)
    {
        string pageCode = "";
        if(currentPage == 1)
        {
            if(totalPage > 1)
            {
                pageCode = "第1页 " + "<a href='" + articleId + "_2.html'>下一页</a> ";
            }
            else
            {
                pageCode = "第1页 ";
            }
        }
        else if(currentPage == totalPage)
        {
            pageCode = "<a href='" + articleId + "_" + (currentPage - 1).ToString() + ".html'>上一页</a> " + "第" + totalPage.ToString() + "页 ";
        }
        else
        {
            pageCode = "<a href='" + articleId + "_" + (currentPage - 1).ToString() + ".html'>上一页</a> "
                + "第" + currentPage.ToString() + "页 " + "<a href='" + articleId + "_" + (currentPage + 1).ToString() + ".html'>下一页</a> ";
        }
        for(int k = 1; k <= totalPage; k++)
        {
            if(k == currentPage)
            {
                pageCode += "<a id='currentPage' href='" + articleId + "_" + k.ToString() + ".html'>" + k.ToString() + "</a> ";
            }
            else
            {
                pageCode += "<a href='" + articleId + "_" + k.ToString() + ".html'>" + k.ToString() + "</a> ";
            }
        }
        return pageCode;
    }
    /// <summary>
    /// 获取短篇文章信息
    /// </summary>
    /// <param name="articleId">要查询的短篇文章ID</param>
    /// <param name="title">返回的文章标题</param>
    /// <param name="author">文章作者</param>
    /// <param name="contentId">内容ID</param>
    /// <param name="content">文章内容</param>
    /// <param name="typeId">文章类型ID</param>
    /// <param name="typeName">文章类型名称</param>
    /// <returns></returns>
    public bool GetShortArticle(string articleId, out string title, out string author, out string contentId, out string content, out string typeId, out string typeName, out string errorMsg)
    {
        title = author = content = contentId = typeId = typeName = "";
        string command = "select a.ArticleTitle,a.Author,c.ContentId,c.ContentPart,p.TypeId,p.TypeName from " + 
            " (ArticleLongTitle a inner join ArticleType p on a.ArticleType=p.TypeId) " + 
            " inner join ArticleLongContent c on a.ArticleId=c.ArticleId " +
            " where a.ArticleId=" + articleId;
        OleDbCommand cmd = new OleDbCommand(command, con);
        try
        {
            con.Open();
            OleDbDataReader reader = cmd.ExecuteReader();
            if(reader.Read())
            {
                title = reader[0].ToString();
                author = reader[1].ToString();
                contentId = reader[2].ToString();
                content = reader[3].ToString();
                typeId = reader[4].ToString();
                typeName = reader[5].ToString();
            }
            reader.Close();
            errorMsg = "";
            return true;
        }
        catch(Exception exs)
        {
            errorMsg = exs.Message;
            return false;
        }
        finally
        {
            con.Close();
        }
    }
    /// <summary>
    /// 生成短篇文章网页
    /// </summary>
    /// <param name="articleId">文章ID</param>
    /// <param name="title">文章标题</param>
    /// <param name="contentId">内容ID</param>
    /// <param name="content">ref 引用 文章内容</param>
    /// <param name="typeId">文章类型ID</param>
    /// <param name="typeName">文章类型名称</param>
    /// <returns></returns>
    protected bool CreateShortArticle(string articleId, string title, string author, string contentId, ref string content, string typeId, string typeName, out string errorMsg)
    {
        try
        {
            using(StreamWriter w = new StreamWriter(HttpContext.Current.Server.MapPath("~\\html\\") + articleId + ".html", false, System.Text.Encoding.UTF8))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(HttpContext.Current.Server.MapPath("~\\App_Data\\ArticleContentTemplate.xml"));
                XmlElement root = doc.DocumentElement;

                w.Write(root.SelectSingleNode("htmlHead").InnerText + title + ",contentId=" + contentId + root.SelectSingleNode("htmlTitleEnd").InnerText +
                    root.SelectSingleNode("htmlContentTitle").InnerText + "<div id='nav'><a href='articlemenu" +//<a href='../default.aspx'>首页</a>
                    typeId + "_1.html'>" + typeName + "</a></div><span id='visitPage'>" + articleId + "</span>" + title + "<span class='author'>作者：" + author + "</span>" + 
                    root.SelectSingleNode("htmlContentHead").InnerText + content + root.SelectSingleNode("htmlEnd").InnerText);
                w.Close();
            }
            errorMsg = "";
            return true;
        }
        catch(Exception exs)
        {
            errorMsg = exs.Message;
            return false;
        }
    }
    private OleDbConnection con = new OleDbConnection(GetConfigContent.ConnectionStringArticle);
}
